package model

import (
	"hft/tools/ws/single_ws/const_val"
	"time"

	"github.com/gorilla/websocket"
)

// 心跳检测
func Heartbeat() {
	for {
		// 获取所有的client
		Manager.Mu.Lock()
		clients := make([]*Client, 0)
		for _, c := range Manager.Clients {
			clients = append(clients, c)
		}
		Manager.Mu.Unlock()
		for _, c := range clients {
			if time.Now().Unix()-c.HeartTime > const_val.MaxHeartTime {
				c.Socket.WriteMessage(websocket.TextMessage, []byte(`长时间未连接,已断开`))
				// 断开连接
				Manager.Unregister <- c
				delete(Manager.Clients, c.ID)
				close(c.Send)
				c.Socket.Close()
			}
		}
		time.Sleep(time.Second * const_val.HeartbeatTime)
	}
}
